package net.wofly.sale.exchange.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import net.wofly.right.domain.Customer;
import net.wofly.right.service.ICustomerService;
import net.wofly.sale.exchange.domain.*;
import net.wofly.sale.exchange.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import net.wofly.common.condition.Condition;
import net.wofly.common.condition.ConditionRelate;
import net.wofly.common.condition.ConditionUtil;
import net.wofly.common.condition.FilterCondition;
import net.wofly.common.condition.Operation;
import net.wofly.common.condition.OrderCondition;
import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.Identities;
import net.wofly.common.util.PageHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.right.domain.Organization;
import net.wofly.right.domain.User;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IUserService;

/**
 * Created by Administrator on 2017/9/28.
 * 
 * @author lign
 *
 */
@Service("iExchangeService")
@Transactional
public class ExchangeServiceImpl implements IExchangeService {

    @Resource
    ICardExchangeService iCardExchangeService;
    @Resource
    IExchangeStockService iExchangeStockService;
    @Resource
    IExchangeConsumeService iExchangeConsumeService;
    @Resource
    IUserService iUserService;
    @Resource
    IExchangeTypeService iExchangeTypeService ;
    
    @Resource
    IOrganizationService iOrganizationService ;
    @Resource
    ICardExchangeContentService iCardExchangeContentService;
    @Resource
    ICustomerService iCustomerService;

    @Override
    public ReturnBean<CardExchange> addCardExchange(CardExchange cardExchange) {
        Long currentTime = System.currentTimeMillis();
        cardExchange.setCardExchangeID(Identities.uuid2());
        cardExchange.setModifyDate(currentTime);

        Integer exchangeTotalNum = 0;
        Integer totalVal = 0;
        List<CardExchangeContent> cardExchangeContents = cardExchange.getCardExchangeContents();
        Set<String> exchangeTypeIDSet = new HashSet<>(cardExchangeContents.size());
        for (CardExchangeContent cardExchangeContent : cardExchangeContents) {
            cardExchangeContent.setCardExchangeContentID(Identities.uuid2());
            cardExchangeContent.setCardExchangeID(cardExchange.getCardExchangeID());
            cardExchangeContent.setModifyDate(currentTime);
            exchangeTotalNum += cardExchangeContent.getExchangeNum();
            totalVal += cardExchangeContent.getSubtotal();
            exchangeTypeIDSet.add(cardExchangeContent.getExchangeTypeID());
        }

        if (exchangeTypeIDSet.size() != cardExchangeContents.size()) {
            return new ReturnBean<>(-1, "卡类型不能重复！");
        }

        cardExchange.setCardTypeNum(cardExchangeContents.size());
        cardExchange.setExchangeTotalNum(exchangeTotalNum);
        cardExchange.setTotalVal(totalVal);

        iCardExchangeContentService.save(cardExchangeContents);
        return new ReturnBean<>(ResultCode.SUCCESS, "保存卡兑换成功", iCardExchangeService.save(cardExchange));
    }

    @Override
    public ReturnBean<ExchangeConsume> addExchangeConsume(ExchangeConsume exchangeConsume) {
        Long currentTime = System.currentTimeMillis();
        exchangeConsume.setExchangeConsumeID(Identities.uuid2());
        exchangeConsume.setModifyDate(currentTime);

        ExchangeStock exchangeStock = iExchangeStockService.findOne(exchangeConsume.getUserID());
        if (exchangeStock != null && exchangeStock.getNum() > exchangeConsume.getConsumeNum()) {
            exchangeStock.setModifyDate(currentTime);
            exchangeStock.setNum(exchangeStock.getNum() - exchangeConsume.getConsumeNum());
        } else {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "兑换数目小于库存数目，不能兑换！");
        }

        iExchangeStockService.save(exchangeStock);

        return new ReturnBean<>(ResultCode.SUCCESS, "兑换消费成功", iExchangeConsumeService.save(exchangeConsume));
    }

    @Override
    public ReturnBean<PageWrapper<ExchangeStock>> getAllExchangeStock(Integer pageNum, Integer pageSize, Condition condition) {
        // 获得分页对象pageable，并且在pageable中页码是从0开始，设定按照sortType升序排列
        Pageable pageable = new PageRequest(pageNum - 1,pageSize);
        Page<ExchangeStock> page;
        if (condition != null) {
            page = iExchangeStockService.findAll(condition.getSpecification(), pageable);
        } else {
            page = iExchangeStockService.findAll(pageable);
        }
        return new ReturnBean<>(ResultCode.SUCCESS, "获取兑换库存成功！", PageHelper.toPage(page));
    }

    @Override
    public ReturnBean<PageWrapper<CardExchange>> getMyCardExchange(String userID, Integer pageNum, Integer pageSize) {
        Condition condition = new Condition();
        
        List<FilterCondition> filterConditionList = new ArrayList<>();
        filterConditionList.add(new FilterCondition(userID, "salesmanUserID", ConditionRelate.and.name(), Operation.eq.name(), 1));
        condition.setFilterCondition(filterConditionList);
        
        List<OrderCondition> orderConditions = new ArrayList<>() ;
        orderConditions.add(new OrderCondition("modifyDate" ,"desc",1)) ;
        condition.setOrderConditions(orderConditions);
        
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), CardExchange.class).getResult();
        
        // 获得分页对象pageable，并且在pageable中页码是从0开始，设定按照sortType升序排列
        Pageable pageable = new PageRequest(pageNum - 1,pageSize);
        Page<CardExchange> page = iCardExchangeService.findAll(condition.getSpecification(), pageable);
        
        formatCardExchangeList(page.getContent());

        return new ReturnBean<>(ResultCode.SUCCESS, "获取我的兑换明细成功！", PageHelper.toPage(page));
    }

    private void formatCardExchangeList(List<CardExchange> cardExchanges){
        for(CardExchange cardExchange : cardExchanges) {
        		User user = iUserService.findOne(cardExchange.getSalesmanUserID());
            if (null != user) {	
                cardExchange.setSalesmanUserName(user.getName());
            }

            Customer customer = iCustomerService.findOne(cardExchange.getCustomerUserID()) ;
            if (null != customer) {
                cardExchange.setCustomerUserName(customer.getCustomerName());
            }
            
            List<CardExchangeContent>  cardExchangeContents = iCardExchangeContentService.findByCardExchangeID(cardExchange.getCardExchangeID()) ;
    		
    			transCardExchangeContent(cardExchangeContents) ;

            cardExchange.setCardExchangeContents(cardExchangeContents);
        }
    }

    @Override
    public ReturnBean<PageWrapper<ExchangeConsume>> getMyExchangeConsume(String userID, Integer pageNum, Integer pageSize) {
        Condition condition = new Condition();
        List<FilterCondition> filterConditionList = new ArrayList<FilterCondition>();
        filterConditionList.add(new FilterCondition(userID, "salesmanID", ConditionRelate.and.name(), Operation.eq.name(), 1));
        condition.setFilterCondition(filterConditionList);
        // 获得分页对象pageable，并且在pageable中页码是从0开始，设定按照sortType升序排列
        Pageable pageable = new PageRequest(pageNum - 1,pageSize);
        Page<ExchangeConsume> page;
//        if (condition != null) {
            page = iExchangeConsumeService.findAll(condition.getSpecification(), pageable);
//        } else {
//            page = iExchangeConsumeService.findAll(pageable);
//        }
        return new ReturnBean<>(ResultCode.SUCCESS, "获取兑换库存成功！", PageHelper.toPage(page));
    }

    @Override
    public ReturnBean<ExchangeStock> getMyExchangeStock(String userID) {
        return new ReturnBean<>(ResultCode.SUCCESS, "获取兑换库存成功！", iExchangeStockService.findOne(userID));
    }

	@Override
	public ReturnBean<PageWrapper<CardExchange>> getAllCardExchange(String salesUserID, String customerUserID,
			Integer pageNum, Integer pageSize) {
		Condition condition = new Condition();
        List<FilterCondition> filterConditionList = new ArrayList<FilterCondition>();
        
        if (StringUtils.isNotEmpty(salesUserID)) {
        		filterConditionList.add(new FilterCondition(salesUserID, "salesmanUserID", ConditionRelate.and.name(), Operation.eq.name(), 1));
        }
        
        if (StringUtils.isNotEmpty(customerUserID)) {
	    		filterConditionList.add(new FilterCondition(customerUserID, "customerUserID", ConditionRelate.and.name(), Operation.eq.name(), 2));
	    }
        
        condition.setFilterCondition(filterConditionList);
        
        List<OrderCondition> orderConditions = new ArrayList<>() ;
        orderConditions.add(new OrderCondition("modifyDate" ,"desc",1)) ;
        condition.setOrderConditions(orderConditions);
        
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), CardExchange.class).getResult();

        Sort sort = new Sort(Sort.Direction.DESC, "modifyDate");
        // 获得分页对象pageable，并且在pageable中页码是从0开始，设定按照sortType升序排列
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
        Page<CardExchange> page = iCardExchangeService.findAll(condition.getSpecification(), pageable);

        formatCardExchangeList(page.getContent());
        
        return new ReturnBean<>(ResultCode.SUCCESS, "获取全部兑换明细成功！", PageHelper.toPage(page));
	}

	@Override
	public ReturnBean<CardExchange> getCardExchangeDetail(String cardExchangeID) {
		CardExchange cardExchange = iCardExchangeService.findOne(cardExchangeID) ;
		if (null == cardExchange) {
			return new ReturnBean<>(ResultCode.ERROR_DATA, "获取兑换详情出错。兑换不存在！");
		}
		
		User user = iUserService.findOne(cardExchange.getSalesmanUserID());
        if (null != user) {
            cardExchange.setSalesmanUserName(user.getName());
        }

        Customer customer = iCustomerService.findOne(cardExchange.getCustomerUserID()) ;
        if (null != customer) {
            cardExchange.setCustomerUserName(customer.getCustomerName());
        }
		
		List<CardExchangeContent>  cardExchangeContents = iCardExchangeContentService.findByCardExchangeID(cardExchangeID) ;
		
		transCardExchangeContent(cardExchangeContents) ;
		
		cardExchange.setCardExchangeContents(cardExchangeContents);
		
		return new ReturnBean<>(ResultCode.SUCCESS, "获取全部兑换明细成功！",cardExchange);
	}
	
	private void transCardExchangeContent(List<CardExchangeContent>  cardExchangeContents) {
		if (null ==  cardExchangeContents) {
			return ;
		}
		
		for(CardExchangeContent cardExchangeContent :cardExchangeContents) {
			ExchangeType exchangeType = iExchangeTypeService.findOne(cardExchangeContent.getExchangeTypeID()) ;
			cardExchangeContent.setExchangeType(exchangeType);
		}
		
		return ;
	}
}
